//
//  GPSRecorderViewController.m
//  Portable Traffic Signal Assistor
//
//  Created by Ding on 8/20/12.
//  Copyright (c) 2012 TTU. All rights reserved.
//

#import "GPSRecorderViewController.h"

@interface GPSRecorderViewController ()

@end

@implementation GPSRecorderViewController
@synthesize GPSInfoLabel=_GPSInfoLabel;
@synthesize RecordGPSButton=_RecordGPSButton;
@synthesize recordGPS=_recordGPS;
@synthesize logFilePath=_logFilePath;
@synthesize timer=_timer;
@synthesize locationManager=_locationManager;
@synthesize gpsLogBufferArray=_gpsLogBufferArray;
@synthesize gpsBufferCount=_gpsBufferCount;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    if (!_locationManager) {
        _locationManager = [[CLLocationManager alloc] init];
        [_locationManager setDelegate:self];
        [_locationManager setDistanceFilter:kCLDistanceFilterNone];
        [_locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
//        [_locationManager startUpdatingLocation];
//        [_locationManager startUpdatingHeading];
    }
    if (!_gpsLogBufferArray) {
        _gpsLogBufferArray=[[NSMutableArray alloc] init];
    }
    if (!_RecordGPSButton) {
        self.RecordGPSButton=[UIButton buttonWithType:UIButtonTypeCustom];
        _RecordGPSButton.frame=CGRectMake(15, 300, 280, 40);
        _RecordGPSButton.layer.cornerRadius = 20;
        [self.RecordGPSButton.layer setMasksToBounds:YES];
        [self.RecordGPSButton.layer setBorderWidth:1.0f];
        [self.RecordGPSButton.layer setBorderColor:[[UIColor lightGrayColor] CGColor]];
        [self.RecordGPSButton setBackgroundColor:[UIColor whiteColor]];
        [self.RecordGPSButton setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
        [_RecordGPSButton setTitle:@"Record GPS" forState:UIControlStateNormal];
//        [_RecordGPSButton setBackgroundColor:[UIColor darkGrayColor]];
        [_RecordGPSButton addTarget:self action:@selector(clickRecordGPSButton:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_RecordGPSButton];
    }
    self.gpsBufferCount=0;
    self.recordGPS=NO;


}

- (void)viewDidUnload
{
    [self setGPSInfoLabel:nil];
    [self setRecordGPSButton:nil];
    self.logFilePath=nil;
    self.timer=nil;
    self.locationManager=nil;
    self.gpsLogBufferArray=nil;
    
    
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}
- (void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO];
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    self.recordGPS=[userDefaults boolForKey:@"recordGPS"];
    if (self.recordGPS) {
        
        [self.RecordGPSButton setTitle:@"Stop Recording" forState:UIControlStateNormal];
        //        [self.RecordGPSButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        [self.RecordGPSButton setBackgroundColor:[UIColor redColor]];
        [self.RecordGPSButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [self.locationManager startUpdatingLocation];
//        [self.locationManager startUpdatingLocation];
        
        
        
    }else {
        
        
        [self.RecordGPSButton setTitle:@"Record GPS" forState:UIControlStateNormal];
        [self.RecordGPSButton setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
        [self.RecordGPSButton setBackgroundColor:[UIColor whiteColor]];
        [self.locationManager stopUpdatingHeading];
//        [self.locationManager stopUpdatingHeading];
        
        
    }
}
- (void) viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
//    self.timer = [NSTimer timerWithTimeInterval:1.0f target:self selector:@selector(updateTimer:) userInfo:nil repeats:YES];
//    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    
}

- (void) viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setBool:self.recordGPS forKey:@"recordGPS"];

}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)dealloc {
    [_GPSInfoLabel release];
    [_RecordGPSButton release];
    [_logFilePath release];
    [_timer release];
    [_locationManager release];
    [_gpsLogBufferArray release];
    [super dealloc];
}

//- (void) clickRecordGPSButton:(id)sender
//{
//    if (self.recordGPS) {
//        self.recordGPS=NO;
////        UIBarButtonItem *button=(UIBarButtonItem *)sender;
//        self.RecordGPSButton.titleLabel.text=@"Record GPS";
//        self.RecordGPSButton.tintColor=nil;
//        
//        //Logfile path
//        NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//        NSString *documentsDir = [documentPaths objectAtIndex:0];
//        NSDate *time=[NSDate date];
//        
//        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//        [formatter setDateFormat:@"yyyymmdd-HH-mm-ss"];
//        NSString *stringFromDate = [formatter stringFromDate:time];
//        self.logFilePath = [[[NSString alloc] initWithFormat:@"%@/%@.gps",documentsDir,stringFromDate] autorelease];
//    }else {
//        self.recordGPS=YES;
//       
//        self.RecordGPSButton.titleLabel.text=@"Stop Recording";
//        self.RecordGPSButton.tintColor=[UIColor redColor];
//    }
//    
//}

- (void)clickRecordGPSButton:(id)sender {
    if (self.recordGPS) {
        self.recordGPS=NO;
        //        UIBarButtonItem *button=(UIBarButtonItem *)sender;
        [self.RecordGPSButton setTitle:@"Record GPS" forState:UIControlStateNormal];
        [self.RecordGPSButton setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
        [self.RecordGPSButton setBackgroundColor:[UIColor whiteColor]];
        
        [self.locationManager stopUpdatingLocation];
        [self.locationManager stopUpdatingHeading];
        
        NSFileHandle *fileHandler = [NSFileHandle fileHandleForUpdatingAtPath:self.logFilePath];
        if (!fileHandler) {
            NSString *content=[NSString stringWithFormat:@"GPS logs from iphone beginning at the time of \n"];
            NSData* data=[content dataUsingEncoding:NSUTF8StringEncoding];
            [data writeToFile:self.logFilePath atomically:YES ];
            fileHandler = [NSFileHandle fileHandleForUpdatingAtPath:self.logFilePath];
        }
        [fileHandler seekToEndOfFile];
        for (int i=0; i<self.gpsLogBufferArray.count; i++) {
            [fileHandler writeData:[[NSString stringWithFormat:@"%@\n",[self.gpsLogBufferArray objectAtIndex:i]] dataUsingEncoding:NSUTF8StringEncoding]];
        }
        self.gpsBufferCount=0;
        [self.gpsLogBufferArray removeAllObjects];
        
        [fileHandler closeFile];
        
        
    }else {
        self.recordGPS=YES;
        [self.RecordGPSButton setTitle:@"Stop Recording" forState:UIControlStateNormal];
//        [self.RecordGPSButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        [self.RecordGPSButton setBackgroundColor:[UIColor redColor]];
        [self.RecordGPSButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [self.locationManager startUpdatingLocation];
        [self.locationManager startUpdatingHeading];
        //Logfile path
        NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDir = [documentPaths objectAtIndex:0];
        NSDate *time=[NSDate date];
        
        NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
        [formatter setDateFormat:@"yyyymmdd-HH-mm-ss"];
        NSString *stringFromDate = [formatter stringFromDate:time];
        self.logFilePath = [[[NSString alloc] initWithFormat:@"%@/%@.gps",documentsDir,stringFromDate] autorelease];

    }
    
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
	
	CLLocationDirection direction=newLocation.course;
    if (direction!=-1) {
        direction=direction*180/M_PI;
    }
    
    
    //    self.heading=direction;
    self.GPSInfoLabel.text=[newLocation.description stringByAppendingFormat:@"\n mageticHeading:%f,courseDirection:%f",self.locationManager.heading.magneticHeading,direction];
    
    if (!self.recordGPS) {
        return;
    }
    
    [self.gpsLogBufferArray addObject:[NSString stringWithFormat:@"%@\n",newLocation.description]];
    self.gpsBufferCount=self.gpsBufferCount+1;
    if (self.gpsBufferCount>=30) {
        NSFileHandle *fileHandler = [NSFileHandle fileHandleForUpdatingAtPath:self.logFilePath];
        if (!fileHandler) {
            NSString *content=[NSString stringWithFormat:@"GPS logs from iphone beginning at the time of \n"];
            NSData* data=[content dataUsingEncoding:NSUTF8StringEncoding];
            [data writeToFile:self.logFilePath atomically:YES ];
            fileHandler = [NSFileHandle fileHandleForUpdatingAtPath:self.logFilePath];
        }
        [fileHandler seekToEndOfFile];
        for (int i=0; i<self.gpsLogBufferArray.count; i++) {
            [fileHandler writeData:[[NSString stringWithFormat:@"%@\n",[self.gpsLogBufferArray objectAtIndex:i]] dataUsingEncoding:NSUTF8StringEncoding]];
        }
        self.gpsBufferCount=0;
        [self.gpsLogBufferArray removeAllObjects];
        
        [fileHandler closeFile];
    }
    
    
    //    NSString *myString; //Assuume the string you want to write is this
    
    
}

//- (void) locationManager:(CLLocationManager *)manager
//        didUpdateHeading:(CLHeading *)newHeading
//{
//    float heading = newHeading.magneticHeading; //in degrees
//    self.heading=heading;
//    
//    //    float headingDegrees = (heading*M_PI/180); //assuming needle points to top of iphone. convert to radians
//    //    self.mapView.transform = CGAffineTransformMakeRotation(headingDegrees);
//}
@end
